/**
 * Created by fly on 2017/4/13.
 * 处理用户相关逻辑
 * 如登陆注册，用户信息等
 */
var db = require('../db/connect_pool');
var Q = require('q');
// var doSqlPromise = require('../tools/promise').doSqlPromise();

function doSqlPromise (sql,value) {
    var deferred = Q.defer();
    db.query(sql,value,function (result) {
        deferred.resolve(result);
    });
    return deferred.promise;
}
/**
 * 用户注册
 * @param userMess 用户信息
 * @param callback 回掉函数
 * 1 表示注册成功 0 表示用户存在，注册失败
 */
exports.userRegister = function (userMess, callback) {
    chargeUser(userMess.tel)
        .then(function (isUser) {
            if(!isUser){
                doSqlPromise('insert into z_user_pass(tel,pass) values(?,?)',[userMess.tel,userMess.pass])
                    .then(function (result) {
                        doSqlPromise(
                            'insert into z_user(nickname,tel,role,user_pass_id) values(?,?,?,?)',
                            [userMess.tel,userMess.tel,0,result.insertId]
                        );
                    }).then(function () {
                        callback(1);
                    });
            }else{
               callback(0)
            }
        });
}
/**
 * 验证用户名是否已经存在
 * @param tel 用户名（手机号）
 * @returns {返回查找数据的长度 0 代表不存在 1 代表存在}
 */
function chargeUser(tel) {
    var deferred = Q.defer();
    doSqlPromise('select * from z_user_pass where tel=?',[tel])
        .then(function (result) {
            deferred.resolve(result.length);
        });
    return deferred.promise;
}
/**
 * 用户登录
 * @param userMess 用户登录信息  包括登录名，密码
 * @param callback 回掉函数
 */
exports.userLogin = function (userMess, callback) {
    chargeUser(userMess.tel)
        .then(function (isExist) {
            if(isExist){
                doSqlPromise('select * from z_user_pass where tel = ? and pass = ? ',
                    [userMess.tel,userMess.pass])
                    .then(function (result) {
                        callback(result.length); // 返回查找字段的长度 0表示密码错误 1表示登陆成功
                    });
            }else{
                callback(-1); // 用户不存在
            }
        })
}
/**
 * 获取登录用户的个人信息
 * @param tel 用户登录手机号，唯一 通过手机号获取个人信息
 * @param callback
 */
exports.getUserMess = function (tel, callback) {
    doSqlPromise('select * from z_user where tel = ?', [tel])
        .then(function (result) {
            callback(result);
        });
}
/**
 * 根据手机号获取用户id
 * @param tel
 * @returns {*|promise}
 */
function getUserId(tel) {
    var deferred = Q.defer();
    db.query('select * from z_user where tel = ?',[tel],function (result) {
        deferred.resolve(result);
    });
    return deferred.promise;
}

/**
 * 下订单逻辑
 * @param data 订单所需数据
 * @param userid 登录用户的id
 * @param callback
 */
exports.placeOrder = function (data, callback) {
    getUserId(data.user)
        .then(function (user) {
            var values = [user[0].id,data.owner_name,data.owner_tel,data.owner_floor_space,data.order_company,data.designer];
            doSqlPromise('insert into fitment_order(userid,username,usertel,floor_space,companyid,designer,fitment_state)' +
                ' values(?,?,?,?,?,?,0)', values)
                .then(function (result) {
                    callback('ok')
                });
        });
}
/**
 * 公司提供免费设计功能逻辑
 * @param data
 * @param callback
 */
exports.freeDesigner = function (data, callback) {
    getUserId(data.user)
        .then(function (user) {
            var values = [user[0].id,data.owner_name,data.owner_tel,data.owner_floor_space,data.order_company,data.designer];
            console.log(values);
            doSqlPromise('insert into free_designer(userid,owner_name,tel,floor_space,companyid,designer,state)' +
                ' values(?,?,?,?,?,?,0)', values)
                .then(function (result) {
                    callback('ok')
                });
        });
}
/**
 * 获取业主的订单
 * @param user 用户手机号
 * @returns {*|promise}
 */
exports.getOrder = function (user) {
    var deferred = Q.defer();
    var userid;
    getUserId(user)
        .then(function (user) {
            userid = user[0].id;
            var sql;
            if(user[0].role == 0){
                sql = 'select * from fitment_order left ' +
                'join z_fitment_company on(z_fitment_company.id = fitment_order.companyid) ' +
                'where userid = ?'
            }else if(user[0].role == 1){
                sql = 'select *,fitment_order.id as orderid from fitment_order \
                left join z_fitment_company on(z_fitment_company.id = fitment_order.companyid) \
                left join z_user on(fitment_order.companyid = z_user.companyid) \
                where z_user.id = ?'
            }else if(user[0].role == 2){
                sql = 'select *,fitment_order.id as orderid from fitment_order \
                left join z_user on(fitment_order.designer = z_user.id) \
                where z_user.id = ?'
            }
            doSqlPromise(sql, [userid])
                .then(function (result) {
                    deferred.resolve(result);
                })
        });
    return deferred.promise;
}
/**
 * 对案例进行评价
 * @param user 登录手机号
 * @param ass_con 评价内容
 * @param ass_score 打分
 * @param caseid 评价的案例的id
 * @param data
 * @returns {*|promise}
 */
exports.assessOrder = function (data) {
    var deferred = Q.defer();
    var userid,users;
    getUserId(data.user)
        .then(function (user) {
            userid = user[0].id;
            users = user;
            var values = [data.ass_con,data.ass_score,data.caseid,userid];
            doSqlPromise('insert into case_assess' +
                '(assess_con,score,caseid,userid) values(?,?,?,?)', values)
                .then(function (result) {
                    deferred.resolve(users);
                })
        })
    return deferred.promise;
}
/**
 * 更改用户信息
 * @param data
 * @param mess包括昵称，手机号，等信息
 * @param add 地址信息 包括省份和城市
 * @returns {*|promise}
 */
exports.alterUserMess = function (data) {
    var deferred = Q.defer();
    var mess = [data.mess.nickname,data.mess.tel,data.add.pro,data.add.city,data.mess.id];
    doSqlPromise('update z_user set nickname=?,tel=?,province=?,city=? where id = ?', mess)
        .then(function (result) {
            deferred.resolve(result);
        });
    return deferred.promise;
}
/**
 * 装修公司接单
 * @param id 订单id
 * @param order
 * @returns {*}
 */
exports.orderTaking = function (order) {
    var deferred = Q.defer();
    doSqlPromise('update fitment_order set fitment_state=1 where id = ?', [order.id])
        .then(function (result) {
            deferred.resolve(result);
        });
    return deferred.promise;
}
/**
 * 获取装修日记
 * @param user 登录用户的手机号
 * @returns {*}
 */
exports.getDiary = function (user) {
    var deferred = Q.defer();
    var userid,sql;
    getUserId(user)
        .then(function (users) {
            userid = users[0].id;
            if(users[0].role == 0){
                sql = 'select * from build_diary where userid = ?';
            }else if(users[0].role == 1){
                sql = 'select * from build_diary LEFT JOIN\
                fitment_order on(build_diary.orderid = fitment_order.id)\
                left join z_user on(fitment_order.companyid = z_user.companyid)\
                where z_user.id = ?';
            }
            doSqlPromise(sql, [userid])
                .then(function (result) {
                    deferred.resolve(result);
                });
        });
    return deferred.promise;
}
/**
 * 添加装修日记
 * @param data
 * @returns {*|promise}
 */
exports.addDiary = function (data) {
    var deferred = Q.defer();
    var userid;
    getUserId(data.user)
        .then(function (users) {
            userid = users[0].id;
            // new Date(new Date('Mon May 08 2017 00:00:00 GMT+0800').toISOString().slice(0,10)).getTime() 转化毫秒
            data.date = new Date(new Date(data.date).toISOString().slice(0,10)).getTime();
            var values = [data.date,data.date,data.con,data.orderid,userid];
            doSqlPromise('insert into build_diary(start,end,title,orderid,userid) values(?,?,?,?,?)', values)
                .then(function (result) {
                    deferred.resolve(result);
                });
        });
    return deferred.promise;
}
/**
 * 获取记账本
 * @param user 登录用户手机号
 * @returns {*|promise}
 */
exports.getCashBook = function (user) {
    var deferred = Q.defer();
    var userid,sql;
    getUserId(user)
        .then(function (users) {
            userid = users[0].id;
            if(users[0].role == 0){
                sql = 'select * from cashbook where userid = ?';
            }else if(users[0].role == 1){
                sql = 'select * from cashbook LEFT JOIN\
                fitment_order on(cashbook.orderid = fitment_order.id)\
                left join z_user on(fitment_order.companyid = z_user.companyid)\
                where z_user.id = ?';
            }
            doSqlPromise(sql, [userid])
                .then(function (result) {
                    deferred.resolve(result);
                });
        });
    return deferred.promise;
}

exports.addCashBook = function (data) {
    var deferred = Q.defer();
    var userid;
    getUserId(data.user)
        .then(function (users) {
            userid = users[0].id;
            var values = [data.goods,data.price,data.orderid,userid];
            doSqlPromise('insert into cashbook(resume,price,orderid,userid) values(?,?,?,?)', values)
                .then(function (result) {
                    deferred.resolve(result);
                });
        });
    return deferred.promise;
}
